<template>
  <div class="salary-container">
    <FeatureHeader img="https://cdn-icons-png.flaticon.com/512/3135/3135715.png" title="工资管理" />
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增工资记录</el-button>
      <el-date-picker
        v-model="selectedMonth"
        type="month"
        placeholder="选择月份"
        style="margin-left: 10px"
        @change="handleMonthChange">
      </el-date-picker>
    </div>

    <el-table :data="filteredSalaryList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="employeeName" label="员工姓名"></el-table-column>
      <el-table-column prop="department" label="部门"></el-table-column>
      <el-table-column prop="position" label="职位"></el-table-column>
      <el-table-column prop="baseSalary" label="基本工资"></el-table-column>
      <el-table-column prop="bonus" label="奖金"></el-table-column>
      <el-table-column prop="deduction" label="扣除"></el-table-column>
      <el-table-column prop="total" label="实发工资"></el-table-column>
      <el-table-column prop="month" label="月份"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="form.employeeId" placeholder="请选择员工" @change="handleEmployeeChange">
            <el-option
              v-for="item in employees"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              v-if="employees && employees.length > 0">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本工资" prop="baseSalary">
          <el-input-number v-model="form.baseSalary" :min="0" :step="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="奖金" prop="bonus">
          <el-input-number v-model="form.bonus" :min="0" :step="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="扣除" prop="deduction">
          <el-input-number v-model="form.deduction" :min="0" :step="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="form.month"
            type="month"
            placeholder="选择月份"
            value-format="yyyy-MM"> <!-- 设置 value-format 为 yyyy-MM -->
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FeatureHeader from '@/components/FeatureHeader.vue'
import BaseTable from '@/components/BaseTable.vue'
import BaseForm from '@/components/BaseForm.vue'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'SalaryList',
  components: { FeatureHeader, BaseTable, BaseForm },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '新增工资记录',
      form: {
        employeeId: '',
        employeeName: '',
        department: '',
        position: '',
        baseSalary: 0,
        bonus: 0,
        deduction: 0,
        total: 0,
        month: ''
      },
      rules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        baseSalary: [{ required: true, message: '请输入基本工资', trigger: 'blur' }],
        bonus: [{ required: true, message: '请输入奖金', trigger: 'blur' }],
        deduction: [{ required: true, message: '请输入扣除金额', trigger: 'blur' }],
        month: [{ required: true, message: '请选择月份', trigger: 'change' }]
      },
      loading: true,
      editMode: false,
      selectedMonth: '' // 用于存储当前选择的月份
    }
  },
  computed: {
    ...mapState({
      salaryList: state => state.salary.list,
      allEmployees: state => state.employee.list // 引入全部员工列表
    }),
    // 将全部员工列表映射为适用于 el-select 的 options 格式
    employees() {
      return this.allEmployees.map(emp => ({ value: emp.id, label: emp.name }));
    },
    // 根据 selectedMonth 筛选 salaryList
    filteredSalaryList() {
      if (!this.selectedMonth) return this.salaryList;
      const month = this.formatMonth(this.selectedMonth);
      return this.salaryList.filter(item => this.formatMonth(item.month) === month);
    }
  },
  async created() {
    await this.fetchList();
    await this.fetchEmployeeList(); // 等待员工列表加载完成
    this.loading = false; // 数据加载完成后再设置 loading 为 false
  },
  methods: {
    ...mapActions({
      fetchList: 'salary/fetchList',
      fetchEmployeeList: 'employee/fetchList', // 引入获取员工列表的 action
      addSalary: 'salary/addSalary',
      editSalary: 'salary/editSalary',
      deleteSalary: 'salary/deleteSalary'
    }),
    handleAdd() {
      this.dialogTitle = '新增工资记录';
      this.editMode = false;
      this.form = { 
        employeeId: '', 
        employeeName: '', 
        department: '', 
        position: '', 
        baseSalary: 0, 
        bonus: 0, 
        deduction: 0, 
        total: 0, 
        month: '' 
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑工资记录';
      this.editMode = true;
      this.form = { ...row, month: this.formatMonth(row.month) }; // 确保 month 是 YYYY-MM 格式
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确认删除该工资记录?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deleteSalary(row.id);
        this.$message.success('删除成功');
      });
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.total = this.form.baseSalary + this.form.bonus - this.form.deduction;
          if (this.editMode) {
            this.editSalary({ ...this.form });
            this.$message.success('编辑成功');
          } else {
            this.addSalary({ ...this.form });
            this.$message.success('新增成功');
          }
          this.dialogVisible = false;
        }
      });
    },
    handleMonthChange() {
      // 根据月份筛选数据
    },
    handleEmployeeChange(id) {
      const emp = this.allEmployees.find(e => e.id === id);
      if (emp) {
        this.form.employeeName = emp.name;
        this.form.department = emp.department || '';
        this.form.position = emp.position || '';
      } else {
        this.form.employeeName = '';
        this.form.department = '';
        this.form.position = '';
      }
    },
    // 格式化月份为 YYYY-MM
    formatMonth(date) {
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.salary-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}
</style>